<?php
namespace app\common\logic;

use app\common\library\exception\ApiException;
use app\common\library\MemberVo;
use app\common\model\Collection;
use app\common\model\Member;
use app\common\model\MemberApply;
use app\common\model\RoleUser;
use app\common\model\Shop;
use app\common\model\ShopMember;
use app\common\model\ShopMemberPermission;
use think\Cache;
use think\Db;
use think\db\Query;
use think\Env;
use think\Exception;


class ShopMemberLogic extends BaseLogic
{
    public $model;

    public function assignModel()
    {
        $this->model          = new ShopMember();
    }

    /**
     * 搜索条件处理
     * @param Query $query
     * @param array $params
     * @return Query
     */
    public function handleSearch(Query $query, array $params): Query
    {
        if (isset($params['keywords']) && !empty($params['keywords'])) {
            $whereOrRaw = "member.member_name LIKE '%{$params['keywords']}%' or member.member_mobile LIKE '%{$params['keywords']}%'";
            $query->whereOrRaw($whereOrRaw);
        }
        if (isset($params['is_del'])) {
            $query->where('shop_member.is_del',$params['is_del']);
        }
        if (isset($params['member_id'])) {
            $query->where('shop_member.member_id',$params['member_id']);
        }
        if (isset($params['shop_id']) && !empty($params['shop_id'])) {
            $query->where('shop_member.shop_id',$params['shop_id']);
        }
        return $query;
    }

    /**
     * 列表
     * @param array $params
     */
    public function index($params)
    {
        $params['is_del'] = 0;
        $params['with'] = ['member'];
        $params['field'] = ['member_id','is_admin'];
        $params['shop_id'] = MemberVo::instance()->getShopId();
        $pageList       = $this->getPageList($params);
        $pageList = $pageList->toArray();
        if (!empty($pageList['data'])) {
            foreach ($pageList['data'] as &$v){
                $v['member_avatar'] = $v['member']['member_avatar'];
                $v['member_name'] = $v['member']['member_name'];
                $v['member_mobile'] = $v['member']['member_mobile'];
                unset($v['member']);
            }
        }
        return $pageList;
    }

    /**
     * 列表
     * @param array $params
     */
    public function apply_index($params)
    {
        $pageList = MemberApply::field('id apply_id,member_id,shop_id,status')
            ->with(['member'])->where(['shop_id'=>$params['shop_id'],'member_apply.status'=>MemberApply::CHECK_PENDING])
            ->order('member_apply.createtime desc')->paginate(10);
        $pageList = $pageList->toArray();
        if (!empty($pageList['data'])) {
            foreach ($pageList['data'] as &$v){
                $v['member_avatar'] = $v['member']['member_avatar'];
                $v['member_name'] = $v['member']['member_name'];
                $v['member_mobile'] = $v['member']['member_mobile'];
                unset($v['member']);
            }
        }
        return $pageList;
    }

    /**
     * 会员申请审核
     * @param array $params
     */
    public function audit($params)
    {
        $apply_info = MemberApply::get($params['apply_id']);
        if (empty($apply_info))
            throw new ApiException('申请信息不存在',404);
        switch ($params['status']){
            case MemberApply::AUDIT_PASS:
                $userInfo = ShopMember::get(['member_id'=>$apply_info['member_id'],'shop_id'=>$params['shop_id']]);
                MemberApply::update(['status'=>2,'audit_time'=>time()],['id'=>$apply_info['id']]);
                if ($userInfo){
                    if ($userInfo['is_del'] == 0){
                        throw new ApiException('该人员已是店铺成员，请勿重复审核',404);
                    }else{
                        ShopMember::update(['is_del'=>0,'is_admin'=>0],['member_id'=>$apply_info['member_id'],'shop_id'=>$params['shop_id']]);
                    }
                }else{
                    ShopMember::create(['is_del'=>0,'member_id'=>$apply_info['member_id'],'shop_id'=>$params['shop_id']]);
                }
                return true;
            case MemberApply::Audit_FAILED:
                MemberApply::update(['status'=>3,'audit_time'=>time()],['id'=>$apply_info['id']]);
                return true;
            default:
                throw new ApiException('参数传递有误',404);
                break;
        }
    }

    public function role_index()
    {

        $member_id = MemberVo::instance()->getMemberId();//获取当前用户id
        $member_type = MemberVo::instance()->getMemberType();//获取当前用户所处的类型 0用户端  1商家端
        $shop_id = MemberVo::instance()->getShopId();
        $member_info = Member::get($member_id); //获取用户信息
        $arr = ['is_selected'=>0,'shop_id'=>0,'member_id'=>$member_id,'is_admin'=>0,'shop_status'=>1,'member_avatar'=>$member_info['member_avatar'],'member_name'=>$member_info['member_name'],'name'=>'车主端','role_name'=>'用户'];
        $list = $this->getList(['member_id'=>$member_id,'is_del'=>0,'with'=>['shop'],'field'=>['shop_id','member_id','is_admin']])->each(function (&$item) use ($shop_id,$member_type,$member_info){
            if ($item['shop']['is_del'] == 0 && $item['shop']['status'] == 1){
                $item['shop_status'] = 1; //店铺状态正常
            }elseif ($item['shop']['is_del'] == 1){
                $item['shop_status'] = 2;//店铺状态被删除
            }elseif ($item['shop']['is_del'] == 0 && $item['shop']['status'] == 0){
                $item['shop_status'] = 0;//店铺状态被停止
            }
            $item['member_avatar'] = $item['shop']['logo'];
            $item['member_name'] = $member_info['member_name'];
            $item['name'] = $item['shop']['shop_name'];
            $item['is_selected'] = 0;
            if ($member_type == 1 && $shop_id == $item['shop_id']){
                $item['is_selected'] = 1;
            }
            $item['role_name'] = $item['is_admin'] == 1 ? '管理员' : '运营者';
            unset($item['shop']);
            return $item;
        });
        if ($member_type == 0){
            $arr['is_selected'] = 1;
        }
        $list[] = $arr;
        return $list;
    }

    /**
     * 角色切换
     * @param $params
     */
    public function exchange($params)
    {
        $member_id = MemberVo::instance()->getMemberId();//获取当前用户id
        $token = MemberVo::instance()->getToken();
        $member_info = Member::get($member_id);
        if ($params['shop_id'] == 0){
            $arr = ['member_id'=>$member_id, 'member_mobile'=>$member_info['member_mobile'], 'member_avatar'=>$member_info['member_avatar'], 'member_name'=>$member_info['member_name'], 'mini_openid'=>$member_info['mini_openid'], 'default_shop_id'=>0, 'token'=>$token, 'member_type'=>0,'role_id'=>0];
            Member::update(['default_shop_id'=>$params['shop_id'],'member_type'=>Member::MEMBER_TYPE_CLIENT],['id'=>$member_id]);
        }else{
            $shopMemberInfo = $this->model->where(['shop_id'=>$params['shop_id'],'member_id'=>$member_id])->find();
            if (!$shopMemberInfo)
                throw new ApiException('店铺无该成员信息',404);
            $shop = Shop::get($params['shop_id']);
            if (!$shop)
                throw new ApiException('无该店铺相关信息',404);
            if ($shop['is_del'] === 1)
                throw new ApiException('该店铺已被删除',404);
            $arr = ['member_id'=>$member_id, 'member_mobile'=>$member_info['member_mobile'], 'member_avatar'=>$member_info['member_avatar'], 'member_name'=>$member_info['member_name'], 'mini_openid'=>$member_info['mini_openid'], 'default_shop_id'=>$params['shop_id'], 'token'=>$token, 'member_type'=>1,'role_id'=>$shopMemberInfo['is_admin'] == 1 ? 1 : 2];
            Member::update(['default_shop_id'=>$params['shop_id'],'member_type'=>Member::MEMBER_TYPE_SHOP],['id'=>$member_id]);
        }
        Cache::store('redis')->set('member_token_'.$member_id,$token,604800); //token缓存
        Cache::store('redis')->rm($token);
        Cache::store('redis')->set($token,json_encode($arr),604800); //保存用户信息
        return $arr;
    }


    /**
     * 删除成员
     * @param $params
     * @return bool
     * @throws ApiException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function del($params)
    {
        $info = $this->first(['member_id'=>$params['member_id'],'shop_id'=>MemberVo::instance()->getShopId(),'is_del'=>0,'is_admin'=>0]);
        if (!$info){
            throw new ApiException('无该成员信息',404);
        }else{
            $info->save(['is_del'=>1]);
        }
        return true;
    }


    /**
     * 成员权限更新
     * @param $params
     * @return bool
     */
    public function update_permission($params)
    {
        Db::startTrans();
        try{
            ShopMemberPermission::where(['shop_id'=>MemberVo::instance()->getShopId(),'member_id'=>$params['member_id']])->delete();
            if (!empty($params['permissions'])){
                $arr = [];
                foreach ($params['permissions'] as $v){
                    if (empty($v))
                        continue;
                    $arr[] = ['shop_id'=>MemberVo::instance()->getShopId(),'member_id'=>$params['member_id'],'permission_id'=>$v,'createtime'=>time()];
                }
                if (!empty($arr))
                    ShopMemberPermission::insertAll($arr);
            }
            Db::commit();
            return true;
        }catch (Exception $e){
            Db::rollback();
            throw new ApiException($e->getMessage(),404);
        }
    }


}